/**
 * 
 */
package ru.etu.game;

import java.util.ArrayList;


import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;

/**
 * @author Alucard
 * @author Neko
 * Движок. Отвечает за отображение на экране, хранение объетов и просчет столкновений. 
 */
public class Engine extends JPanel {
	public Engine() {
		setBackground(Color.BLACK);		
		gameObjects = new ArrayList<Sprite>();	
		stopped = false;
		setFocusable(true);
	}
	
	void addEnemy(int numEnemy, int pos){
		try{
			Image img = ImageIO.read(new File("tank.gif"));
			Enemy p = new Enemy();
			p.Add(new StaticSprite(img, new Point(200,200,40)));
			gameObjects.add(p);		
		}
		catch (Exception e) {
			
		}		
	}
	void addPlayer(int numPlayer){
		
		try{
			Image img = ImageIO.read(new File("tank.gif"));
			Player p = new Player();
			p.Add(new StaticSprite(img, new Point(40,40,40)));
			gameObjects.add(p);
			addKeyListener(p.getListener());							
		}
		catch (Exception e) {
			
		}
	}
	void addBullet(){
		try{
			Image img = ImageIO.read(new File("tank.gif"));
			Bullet p = new Bullet();
			p.Add(new StaticSprite(img, new Point(300,40,40)));
			p.setFront(Direction.LEFT);
			gameObjects.add(p);						
		}
		catch (Exception e) {
			
		}
	}

	@SuppressWarnings("null")
	public void updateWorld() {
		if (!stopped){
			Sprite with=null;
			for (Sprite s: gameObjects){
				if (s instanceof DynamicSprite ){				
					if (testColision((DynamicSprite)s,with)){
						with.collision(s);
						s.collision(with);
					}
					else 
						((DynamicSprite) s).doMove();								
				}			
			}
		}
		
	}
	
	@Override
	protected void paintComponent(Graphics g) {	
		super.paintComponent(g);
		/*buffer = createImage(WIDTH, HEIGHT);
		Graphics back = buffer.getGraphics();*/
		g.setColor(Color.BLACK);
		g.drawRect(0, 0, WIDTH, HEIGHT);
		for (Sprite s: gameObjects){
			s.draw(g);
		}	
	}

	public void pause(){
		stopped = stopped^true;
	}
	public void reset(){
		gameObjects.clear();
	}
	public void load(String fileName){
	
	}
	
	public void save(String fileName){

	}

	public static final int MINIMAL_MOVE = 5; 

	
	private boolean testColision(DynamicSprite s, Sprite with) {
		Point p = s.getNewPosition();
		if (p.getX()<0)
			return false;
		return false;		
	}
	
	private ArrayList<Sprite> gameObjects;
	private boolean stopped;
	private final int WIDTH = 400;
	private final int HEIGHT = 400;

	/**
	 * 
	 */
	private static final long serialVersionUID = -4686230278826631790L;
}
